package org.boot.chat.data.model.dao;

import org.boot.chat.data.model.entity.ChatModelDO;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Repository
public class ChatModelRepository {

    private final JdbcTemplate jdbc;

    public ChatModelRepository(JdbcTemplate jdbc) {
        this.jdbc = jdbc;
    }

    private ChatModelDO rowMapper(ResultSet rs, int i) throws SQLException {
        ChatModelDO e = new ChatModelDO();
        e.setId(rs.getLong("id"));
        e.setBean(rs.getString("bean"));
        e.setApiKey(rs.getString("api_key"));
        e.setBaseUrl(rs.getString("base_url"));
        e.setModel(rs.getString("model"));
        e.setPrimary(rs.getInt("primary"));
        e.setStatus(rs.getInt("status"));
        e.setNote(rs.getString("note"));
        return e;
    }

    public long insert(ChatModelDO e) {
        String sql = """
                INSERT INTO easychat_model_data(bean, api_key, base_url, model, `primary`, status, note)
                VALUES (?,?,?,?,?,?,?)
                """;
        KeyHolder kh = new GeneratedKeyHolder();
        jdbc.update(con -> {
            PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            ps.setString(1, e.getBean());
            ps.setString(2, e.getApiKey());
            ps.setString(3, e.getBaseUrl());
            ps.setString(4, e.getModel());
            ps.setInt(5, e.getPrimary());
            ps.setInt(6, e.getStatus());
            ps.setString(7, e.getNote());
            return ps;
        }, kh);
        return kh.getKey().longValue();
    }

    public int update(ChatModelDO e) {
        String sql = """
                UPDATE easychat_model_data
                SET api_key = ?, base_url = ?, model = ?, `primary` = ?, status = ?, note = ?
                WHERE bean = ?
                """;
        return jdbc.update(sql,
                e.getApiKey(), e.getBaseUrl(), e.getModel(), e.getPrimary(),
                e.getStatus(), e.getNote(), e.getBean());
    }

    public int deleteByBean(String bean) {
        return jdbc.update("DELETE FROM easychat_model_data WHERE bean = ?", bean);
    }


    public Optional<ChatModelDO> findById(Long id) {
        String sql = "SELECT * FROM easychat_model_data WHERE id = ?";
        try {
            return Optional.ofNullable(jdbc.queryForObject(sql, this::rowMapper, id));
        } catch (EmptyResultDataAccessException ex) {
            return Optional.empty();
        }
    }

    public List<ChatModelDO> listAll() {
        String sql = "SELECT * FROM easychat_model_data ORDER BY `primary` DESC, id ASC";
        return jdbc.query(sql, this::rowMapper);
    }
    //条件查询
    public List<ChatModelDO> list(ChatModelDO chatModelDO){
        String sql = "SELECT * FROM easychat_model_data WHERE 1=1";
        List<Object> params = new ArrayList<>();

        if(chatModelDO != null){
            if (chatModelDO.getBean() != null) {
                sql += " AND bean = ?";
                params.add(chatModelDO.getBean());
            }
            if (chatModelDO.getApiKey() != null) {
                sql += " AND api_key = ?";
                params.add(chatModelDO.getApiKey());
            }
            if (chatModelDO.getBaseUrl() != null) {
                sql += " AND base_url = ?";
                params.add(chatModelDO.getBaseUrl());
            }
            if (chatModelDO.getModel() != null) {
                sql += " AND model = ?";
                params.add(chatModelDO.getModel());
            }
            if (chatModelDO.getPrimary() != null) {
                sql += " AND `primary` = ?";
                params.add(chatModelDO.getPrimary());
            }
            if (chatModelDO.getStatus() != null) {
                sql += " AND status = ?";
                params.add(chatModelDO.getStatus());
            }
            if (chatModelDO.getNote() != null) {
                sql += " AND note = ?";
                params.add(chatModelDO.getNote());
            }
        }

        return jdbc.query(sql, this::rowMapper, params.toArray());
    }

}